package com.it.nongchanping.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.util.StringUtils;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin/gallery")
public class AdminGalleryController {

    private final Path uploadPath = Paths.get("src/main/resources/static/images");

    @GetMapping("")
    public String showGallery(Model model) throws IOException {
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        List<String> imageNames = new ArrayList<>();
        File[] files = uploadPath.toFile().listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    imageNames.add(file.getName());
                }
            }
        }

        model.addAttribute("images", imageNames);
        model.addAttribute("title", "图库管理");
        model.addAttribute("activePage", "gallery");
        return "admin/gallery/list";
    }

    @GetMapping("/api/images")
    @ResponseBody
    public ResponseEntity<List<String>> getImages() throws IOException {
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        List<String> imageNames = new ArrayList<>();
        File[] files = uploadPath.toFile().listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    imageNames.add(file.getName());
                }
            }
        }

        return ResponseEntity.ok(imageNames);
    }

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("error", "上传失败，请选择一个文件。");
            return "redirect:/admin/gallery";
        }

        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = StringUtils.getFilenameExtension(originalFilename);
        String newFilename = UUID.randomUUID().toString() + "." + fileExtension;

        try (InputStream inputStream = file.getInputStream()) {
            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            redirectAttributes.addFlashAttribute("message", "图片 '" + originalFilename + "' 上传成功！");
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "上传失败：" + e.getMessage());
        }

        return "redirect:/admin/gallery";
    }

    @GetMapping("/delete")
    public String deleteImage(@RequestParam("filename") String filename, RedirectAttributes redirectAttributes) {
        try {
            Path filePath = uploadPath.resolve(filename);
            if (Files.exists(filePath)) {
                Files.delete(filePath);
                redirectAttributes.addFlashAttribute("message", "图片 '" + filename + "' 删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("error", "删除失败：文件不存在。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
        }

        return "redirect:/admin/gallery";
    }
} 